package com.meow_woof.utils;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.meow_woof.utils.RedisConstants.CACHE_NULL_TTL;

@Component
@Slf4j
public class CacheClient {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR= Executors.newFixedThreadPool(10);
    private Boolean tryLock(String key){
        return stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);

    }
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

    public void set(String key,Object value,Long time,TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }
    public void setWithLogicalExpire(String key,Object value,Long time,TimeUnit unit){
        RedisData redisData=new RedisData();
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        redisData.setData(value);
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));
    }
    public <R,ID> R queryWithPassThrough(String cacheKeyPrefix, ID id, Class<R> type, Function<ID,R> dbFallBack,Long time,TimeUnit unit){
        String key=cacheKeyPrefix+id;
        String cache = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(cache)){
            return JSONUtil.toBean(cache, type);

        }
        if(cache!=null){
            return null;
        }
        R r=dbFallBack.apply(id);
        if(r==null){
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        set(key,JSONUtil.toJsonStr(r),time+ Long.parseLong(RandomUtil.randomNumbers(1)), unit);

        return r;
    }
    public <R,ID> R queryWithLogicalExpire(String cacheKeyPrefix,String lockKeyPrefix, ID id, Class<R> type, Function<ID,R> dbFallBack,Long time,TimeUnit unit){
        String key=cacheKeyPrefix+id;
        String cache = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isBlank(cache)){

            return null;
        }
        RedisData redisData = JSONUtil.toBean(cache, RedisData.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        JSONObject data = (JSONObject) redisData.getData();
        R r = JSONUtil.toBean(data,type);
        if(expireTime.isAfter(LocalDateTime.now())){
            return r;
        }


        String lockKey=lockKeyPrefix+id;
        Boolean isLock = tryLock(lockKey);
        if(isLock){
            if(expireTime.isAfter(LocalDateTime.now())){
                return r;
            }
            CACHE_REBUILD_EXECUTOR.submit(()->{
                R newR=dbFallBack.apply(id);
                setWithLogicalExpire(key,newR,time,unit);

                try {

                    setWithLogicalExpire(key,newR,time,unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unlock(lockKey);
                }



            });




        }



        return r;

    }
    public <R,ID> R queryWithMutex(String cacheKeyPrefix, String lockKeyPrefix,ID id, Class<R> type, Function<ID,R> dbFallBack,Long time,TimeUnit unit){
        String cacheKey=cacheKeyPrefix+id;
        String cache = stringRedisTemplate.opsForValue().get(cacheKey);
        if(StrUtil.isNotBlank(cache)){
            return JSONUtil.toBean(cache, type);

        }
        if(cache!=null){
            return null;
        }

        R r;
        String lockKey=lockKeyPrefix+id;
        try {
            boolean isLock=tryLock(lockKey);
            if(!isLock){
                Thread.sleep(50);
                return queryWithMutex(cacheKeyPrefix,lockKeyPrefix,id,type,dbFallBack,time,unit);


            }
            r = dbFallBack.apply(id);
            if(r==null){
                set(cacheKey,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
                return null;
            }


            set(cacheKey,r,time,unit);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unlock(lockKey);

        }
        return r;
    }


    @Autowired
    private BloomFilterHelper bloomFilterHelper; // 封装 Redisson 的布隆过滤器

    public <R,ID> R queryWithBloom(
            String cacheKeyPrefix,
            ID id,
            Class<R> type,
            Function<ID,R> dbFallBack,
            Long time,
            TimeUnit unit) {

        // 1. 先查布隆过滤器
        if (!bloomFilterHelper.mightContain(Long.valueOf(id.toString()))) {
            return null; // 一定不存在，直接拦截
        }

        // 2. 查缓存
        String key = cacheKeyPrefix + id;
        String cache = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(cache)) {
            return JSONUtil.toBean(cache, type);
        }
        if (cache != null) {
            return null; // 命中缓存空对象
        }

        // 3. 查数据库
        R r = dbFallBack.apply(id);
        if (r == null) {
            // 写入空对象，防止布隆误判
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }

        // 4. 正常写入缓存，并补充进布隆过滤器
        set(key, JSONUtil.toJsonStr(r), time, unit);
        bloomFilterHelper.add(Long.valueOf(id.toString()));

        return r;
    }

    public <R,ID> R queryWithPassThrough(
            String cacheKeyPrefix,
            ID id,
            Class<R> type,
            Function<ID,R> dbFallBack,
            Long time,
            TimeUnit unit,
            String bloomFilterKey) {

        // 1. 布隆过滤器预检
        Boolean mightExist = (Boolean) stringRedisTemplate
                .execute((connection) -> connection.execute(Arrays.toString("BF.EXISTS".getBytes()),
                                bloomFilterKey.getBytes(),
                                id.toString().getBytes()),
                        true);

        if (Boolean.FALSE.equals(mightExist)) {
            // 一定不存在，直接返回
            return null;
        }

        // 2. 查询缓存
        String key = cacheKeyPrefix + id;
        String cache = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(cache)) {
            return JSONUtil.toBean(cache, type);
        }
        if (cache != null) {
            return null;
        }

        // 3. 查询数据库
        R r = dbFallBack.apply(id);
        if (r == null) {
            // 回写空对象，防止缓存穿透
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }

        // 4. 正常写入缓存
        set(key, JSONUtil.toJsonStr(r),
                time + Long.parseLong(RandomUtil.randomNumbers(1)), unit);

        // 5. 将新 ID 加入布隆过滤器（如果是新写入）
        stringRedisTemplate
                .execute((connection) -> connection.execute(Arrays.toString("BF.ADD".getBytes()),
                                bloomFilterKey.getBytes(),
                                id.toString().getBytes()),
                        true);

        return r;
    }




}
